package com.tanhua.sms;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;


/*
    发送短信模板对象
*
* */
@Slf4j
public class SmsTemplate {

    private SmsProperties smsProperties;

    public SmsTemplate(SmsProperties smsProperties) {
        this.smsProperties = smsProperties;
    }

    public String sendSms(String mobile) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                smsProperties.getAccessKey(), smsProperties.getSecret());
        IAcsClient client = new DefaultAcsClient(profile);

        //随机生成验证码
        String code = RandomUtils.nextInt(100000, 999999) + "";

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", mobile); //目标手机号
        request.putQueryParameter("SignName", smsProperties.getSignName()); //签名名称
        request.putQueryParameter("TemplateCode", smsProperties.getTemplateCode()); //短信模板code
        request.putQueryParameter("TemplateParam", "{\"code\":" + code + "}");//模板中变量替换
        try {
            CommonResponse response = client.getCommonResponse(request);

            //{"Message":"OK","RequestId":"EC2D4C9A-0EAC-4213-BE45-CE6176E1DF23","BizId":"110903802851113360^0","Code":"OK"}
            System.out.println(response.getData());
        } catch (Exception e) {
            log.error("发送验证码失败!",e);
            return null;
        }
        return code;
    }

}
